package dao

import (
	"context"
	"gitee.com/chunanyong/zorm"
	"gitee.com/xinshortlink/internal/constants"
	"gitee.com/xinshortlink/internal/dal/db/model"
	"gitee.com/xinshortlink/internal/dto/resp/bizerr"
	"go.uber.org/zap"
)

type AccountDao struct {
	logger *zap.Logger
}

func NewAccountDao(logger *zap.Logger) *AccountDao {
	return &AccountDao{logger: logger}
}

func (dao *AccountDao) Create(ctx context.Context, account *model.AccountStruct) error {
	_, err := zorm.Insert(ctx, account)
	if err != nil {
		return bizerr.New(bizerr.DB, "创建账户出错", err)
	}
	return nil
}

func (dao *AccountDao) FindByAccountName(ctx context.Context, accountName string) (*model.AccountStruct, error) {
	account := &model.AccountStruct{}

	finder := zorm.NewSelectFinder(account.GetTableName())
	finder.Append("WHERE account_name = ? AND del_state = ?", accountName, constants.NO)

	has, err := zorm.QueryRow(ctx, finder, account)

	if err != nil {
		return nil, bizerr.New(bizerr.DB, "查询账户信息出错", err)
	}

	if !has {
		return nil, nil
	}

	return account, nil
}

func (dao *AccountDao) Update(ctx context.Context, account *model.AccountStruct) error {
	_, err := zorm.UpdateNotZeroValue(ctx, account)
	if err != nil {
		return bizerr.New(bizerr.DB, "更新账户信息出错", err)
	}
	return err
}

func (dao *AccountDao) FindAccountById(ctx context.Context, id int64) (*model.AccountStruct, error) {
	account := &model.AccountStruct{}

	finder := zorm.NewSelectFinder(account.GetTableName()).Append("WHERE id = ? AND del_state = ?", id, constants.NO)

	has, err := zorm.QueryRow(ctx, finder, account)

	if err != nil {
		return nil, bizerr.New(bizerr.DB, "查询账户信息出错", err)
	}

	if !has {
		return nil, nil
	}

	return account, nil
}
